<?php
class App_Page_Model_Layout extends Main_Db_Table_Abstract
{
	/**
	 * @var string
	 */
	protected $_name = 'layout';
	
	/**
	 * @var string
	 */
	protected $_primary = 'id';
	
	/**
	 * @var array
	 */
	protected $_fields = array(
		'id',
	    'name',  
	);
	
	/**
	 * 
	 * @var App_Page_Model_LayoutI18n
	 */
	protected $_modelLayoutI18n;	
	
	/**
	 * @return void
	 */
	public function init() 
	{
		$this->_modelLayoutI18n = Main_Model::factory('Page_Model_LayoutI18n');
	}

	/**
	 * @param array $data
	 * @return bool
	 */
	public function insertItem($data) 
	{
		$dataOk = $this->beforeSave($data, array(
			'name',  
		), array(
			'name',
		));
		
		$result = $this->insert($dataOk);
				
		$data['layout_id'] = $this->lastInsertId(); 
		$res1 = $this->_modelLayoutI18n->insertItem($data);
		
		return $result && $res1;
	}
	
	/**
	 * @param array $data
	 * @param int $id
	 * @return bool
	 */
	public function updateItem($data, $id)
	{
		$id = $this->escape($id);
		$dataOk = $this->beforeSave($data, array(
			'name',  
		), array(
			'name',
		));
    	
		$res1 = $this->_modelLayoutI18n->updateItem($data, $id);
		$res2 = $this->update($dataOk, "id={$id}");  	
		
    	return $res1 && $res2;
	}
	
	/**
	 * @param int $id
	 * @param int $langId
	 * @return array
	 */
	public function getItemById($id, $langId) 
	{
		$id = $this->escape($id);
		
		$sql = "
			SELECT 
				l.id
				, l.name
				, l_i18n.title
			FROM
				layout l
			INNER JOIN
				layout_i18n l_i18n
				ON
					(l.id=l_i18n.layout_id AND l_i18n.lang_id={$langId})		
			WHERE
				l.id={$id}		
		";
				
		$list = $this->getAdapter()->fetchRow($sql);
		return $list;
	}
	
	/**
	 * @param string $name
	 * @param int $langId
	 * @return array
	 */
	public function getItemByName($name, $langId) 
	{
		$name = $this->escape($name);
		
		$sql = "
			SELECT 
				l.id
				, l.name
				, l_i18n.title
			FROM
				layout l
			INNER JOIN
				layout_i18n l_i18n
				ON
					(l.id=l_i18n.layout_id AND l_i18n.lang_id={$langId})		
			WHERE
				l.name='{$name}'		
		";
				
		$list = $this->getAdapter()->fetchRow($sql);
		return $list;
	}
	
	
	/**
	 * @param int $langId
	 * @return array
	 */
	public function getAllIdAndName($langId) 
	{
		$langId = $this->escape($langId);
		
		$sql = "
			SELECT 
				l.id
				, l.name
				, l_i18n.title
			FROM
				layout l
			INNER JOIN
				layout_i18n l_i18n
				ON
					(l.id=l_i18n.layout_id AND l_i18n.lang_id={$langId})
		";
		
		$list = $this->getAdapter()->fetchAll($sql);
		
		$res = Main_Function::expandList($list, 'id', 'title');

		return $res;
	}
	
	/**
	 * @param int $id
	 * @return bool
	 */
	public function deleteItem($id) 
	{
		$id = $this->escape($id);
		if ($this->_modelLayoutI18n->deleteItemByLayoutId($id)) {
			return $this->delete("id={$id}");
		} else {
			return false;
		}	
	}
	
} 
